package com.wstuo.common.tools.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.opensymphony.xwork2.ActionContext;
import com.wstuo.common.tools.dao.IExportInfoDAO;
import com.wstuo.common.tools.dto.ExportInfoDTO;
import com.wstuo.common.tools.entity.ExportInfo;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.util.TimeUtils;

/**
 * 导出信息Service
 * 
 * @author Administrator
 * 
 */
public class ExportInfoService implements IExportInfoService {
	@Autowired
	private IExportInfoDAO exportInfoDAO;
	private final static Logger LOGGER = Logger
			.getLogger(ExportInfoService.class);

	/**
	 * 获取导出信息所有
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findExportInfoPager(ExportInfoDTO exportInfoDTO, int start,
			int limit, String sord, String sidx) {
		PageDTO page = exportInfoDAO.findExportInfoPager(exportInfoDTO, start,
				limit, sord, sidx);
		List<ExportInfo> entities = (List<ExportInfo>) page.getData();
		List<ExportInfoDTO> dtos = new ArrayList<ExportInfoDTO>();
		for (ExportInfo entity : entities) {
			ExportInfoDTO dto = new ExportInfoDTO();
			ExportInfoDTO.entity2dto(entity, dto);
			dtos.add(dto);
		}
		page.setData(dtos);
		return page;
	}

	/**
	 * 删除导出信息
	 * 
	 * @param ids
	 */
	@Transactional
	public void deleteExportInfo(Long[] ids) {
		exportInfoDAO.deleteByIds(ids);
	}

	/**
	 * 保存导出信息
	 */
	@Transactional
	public ExportInfo saveExportInfoReturnEntity(String type) {
		String fileName = type + "_" +TimeUtils.format(new Date(), "yyyyMMddHHmmss") + ".csv";
		ExportInfo exportInfo = new ExportInfo();
		exportInfo.setExportType(type);
		exportInfo.setExportFileName(fileName.trim());
		exportInfo.setExportsSatus("exportWait");
		Long companyNo = 0l;
		if(null != ActionContext.getContext() && null != ActionContext.getContext().getSession()
				&& null != ActionContext.getContext().getSession().get("companyNo")){
			companyNo = Long.parseLong(ActionContext.getContext().getSession().get("companyNo").toString());
		}
		exportInfo.setCompanyNo(companyNo);
		exportInfoDAO.save(exportInfo);
		return exportInfo;
	}

	/**
	 * 导出csv公共方法
	 */
	@Transactional
	public void exportCommonCSV(List<String[]> data, ExportInfo entity,String path) {
		String filePath = path + "/" + entity.getExportFileName();
		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		csvw.writeAll(data);
		OutputStream stream1 = null;
		try {
			stream1 = new FileOutputStream(filePath);
			stream1.write(sw.getBuffer().toString().getBytes("GBK"));
			
			File file = new File(filePath);
			
			entity.setExportFileSize(AppConfigUtils.getInstance().getFileSizes(
					file));
			entity.setExportsSatus("exportComplete");
			exportInfoDAO.update(entity);
		} catch (FileNotFoundException e) {
			LOGGER.error("导出csv公共方法3", e);
		} catch (IOException e) {
			LOGGER.error("导出csv公共方法1", e);
		} catch (Exception e) {
			LOGGER.error("导出csv公共方法2", e);
		} finally {
			try {
				if (stream1 != null) {
					stream1.flush();
					stream1.close();
				}
				if (csvw != null) {
					csvw.flush();
					csvw.close();
				}
				if (sw != null) {
					sw.flush();
					sw.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
	}
	/**
	 * 导出普通CSV文件；
	 * @param path 导出路径
	 * @param data 导出的数据
	 */
	public void exportCSV(String path,List<String[]> data){
		String filePath = path;
		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		OutputStream stream1 = null;
		try {
			csvw.writeAll(data);
			stream1 = new FileOutputStream(filePath);
			stream1.write(sw.getBuffer().toString().getBytes("GBK"));
		} catch (Exception e1) {
			LOGGER.error(e1);
		}finally{
			try {
				if (stream1 != null) {
					stream1.flush();
					stream1.close();
				}
				if (csvw != null) {
					csvw.flush();
					csvw.close();
				}
				if (sw != null) {
					sw.flush();
					sw.close();
				}
			} catch (IOException e) {
				LOGGER.error(e);
			}
		}
	}
}
